import os
from datetime import datetime

from book import Book, ContentType
from utils import LOG
from .pdf_parser import PDFParser

class Writer:
    def __init__(self):
        pass

    @staticmethod
    def _save_translated_book_markdown(book, output_file_path):
        # output_file_path: ./book1
        # output_file_template: book1_translated
        # output_file_name: book1_translated.md
        # output_file_path: ./book1/book1_translated.md
        # img_file_path: ./book1/book1_translated_images
        # ![book1-1](book1_translated_images/book1-1.png)
        output_file_dir = output_file_path
        output_file_template = os.path.basename(output_file_dir) + '_translated'

        output_file_name = output_file_template + '.md'
        output_file_path = os.path.join(output_file_dir, output_file_name)

        img_file_name = output_file_template + '_images'
        img_file_path = os.path.join(output_file_dir, img_file_name)
        os.makedirs(img_file_path, exist_ok=True)

        with open(output_file_path, 'w', encoding='utf-8') as output_file:
            for page_idx, page in enumerate(book.pages):
                for content in page.contents:
                    if content.status:
                        if content.content_type == ContentType.TEXT or content.content_type == ContentType.TABLE:
                            text = content.translation
                            output_file.write(text + '\n\n')
                        elif content.content_type == ContentType.IMAGE:
                            current_time = datetime.now()
                            time_str = current_time.strftime("%Y%m%d%H%M%S%f")[:-3]
                            img_name = f'{output_file_template}-{time_str}'
                            img_sava_path = os.path.join(img_file_path, f'{img_name}.png')
                            content.original.save(img_sava_path)
                            text = f'![{img_name}]({img_file_name}/{img_name}.png)'
                            output_file.write(text + '\n\n')
                    else:
                        error_message = f"Failed to translate content: \n{content.original}\nSkipping...\n"
                        output_file.write(error_message)

                output_file.write(f'--- page {page_idx} ---\n\n')



    def save_translated_book(self, book, output_file_path, file_format: str = 'markdown'):
        if file_format.lower() == 'markdown':
            self._save_translated_book_markdown(book, output_file_path)
        else:
            raise ValueError(f'Unsupported file format: {file_format}')